package com.eascs.web.p2p.member.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.p2p.common.constants.SendType;
import com.eascs.p2p.common.dto.MessageDTO;
import com.eascs.p2p.common.dto.MessageReceiver;
import com.eascs.p2p.common.entity.InvestorEntity;
import com.eascs.p2p.common.security.MD5;
import com.eascs.p2p.common.service.IMessageService;
import com.eascs.p2p.common.service.IMsgSmsService;
import com.eascs.p2p.common.service.InvestorService;
import com.eascs.p2p.common.vo.ModelResult;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.view.BaseRestResult;
import com.eascs.web.p2p.member.form.RegisterForm;
import com.eascs.web.p2p.member.untils.CusAccessObjectUtil;
import com.eascs.web.p2p.member.untils.ValiCodeUtils;

@RestController
public class LoginRestController extends BaseRestController {
	private final Logger logger = LoggerFactory.getLogger(LoginRestController.class);

	@Reference
	InvestorService investorService;
	@Reference
	IMessageService messageService;
	@Reference
	IMsgSmsService msgSmsService;

	public static ModelResult<InvestorEntity> isLogin(HttpServletRequest request) {
		ModelResult<InvestorEntity> result = new ModelResult<>();
		try {
			HttpSession session = request.getSession();
			Object obj = session.getAttribute("member");
			if (obj != null) {
				result.withModel((InvestorEntity) obj);
			}
		} catch (Exception e) {
			result.withError("LoginRestController.isLogin", "session获取登陆用户失败");
			e.printStackTrace();
		}
		return result;
	}
	
	public ModelResult<Boolean> resetLoginInfo(HttpServletRequest request) {
		ModelResult<Boolean> result = new ModelResult<>();
		try {
			HttpSession session = request.getSession();
			Object obj = session.getAttribute("member");
			if (obj != null) {
				InvestorEntity investor=(InvestorEntity) obj;
				ModelResult<InvestorEntity> modelResult = investorService.queryInvestorById(investor.getId());
				if (modelResult.isSuccess()) {
					investor = modelResult.getModel();
					if (investor != null) {
						session.removeAttribute("member");
						session.setAttribute("member", investor);
						result.withModel(true);
					}
				}
			}
		} catch (Exception e) {
			result.withModel(false);
			result.withError("LoginRestController.isLogin", "session获取登陆用户失败");
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping(value = "/ajax/isLogin", method = RequestMethod.GET)
	@ResponseBody
	public BaseRestResult<InvestorEntity> ajaxLogin(HttpServletRequest request) {
		ModelResult<InvestorEntity> modelResult=LoginRestController.isLogin(request);
		if(modelResult.isSuccess()){
			return BaseRestResult.buildRestResult(modelResult.getModel());
		}
		return null;
	}
	
	@RequestMapping(value = "/ajaxVerificationCode", method = RequestMethod.GET)
	@ResponseBody
	public BaseRestResult<Boolean> ajaxVerificationCode(HttpServletRequest request) {
		ModelResult<InvestorEntity> modelResult = LoginRestController.isLogin(request);
		if (!modelResult.isSuccess() || modelResult.getModel() == null) {
			return BaseRestResult.buildRestResult(false);
		}
		InvestorEntity investor=modelResult.getModel();
		MessageDTO msg=new MessageDTO();
		List<MessageReceiver> receivers=new ArrayList<>();
		receivers.add(new MessageReceiver(investor.getAccount(), investor.getMobile()));
		msg.setSendType(SendType.NOW);
		msg.setMsgContent("P2P金融注册验证码:"+ValiCodeUtils.generateCode());
		msg.setSenderName("系统");
		msg.setReceivers(receivers);
		ModelResult<Boolean> msgModelResult =messageService.sendMsg(msg);
		if(msgModelResult.isSuccess()){
			return BaseRestResult.buildRestResult(msgModelResult.getModel());
		}
		return BaseRestResult.buildRestResult(false);
	}
	
	/**
	 * 修改登录密码
	 * @param request
	 * @param response
	 * @param erifyCode
	 * @param pw
	 * @param repeatPW
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/resetPwd/ajaxSubmit")
	public BaseRestResult<?> submitResetPwd(HttpServletRequest request, HttpServletResponse response, 
			String mobile, String smsCode, String password) throws Exception{
		if (StringUtil.isEmpty(mobile) || StringUtil.isEmpty(smsCode) || StringUtil.isEmpty(password)) {
			logger.info("修改登录密码失败，参数不能为空,mobile:{},smsCode:{},password:{}", mobile, smsCode, password);
			BaseRestResult.error("修改登录密码失败，参数不能为空");
		}
		// TODO 手机短信 确认验证码
		ModelResult<Boolean> checkResult = msgSmsService.useAuthCode(mobile, smsCode);
		if(checkResult.isSuccess() && checkResult.getModel()){
			InvestorEntity updateObj = investorService.queryInvestorByAccount(mobile).getModel();
			if(null == updateObj){
				response.sendRedirect("/member/index");
				return BaseRestResult.error("用户账号不存在");
			}
			password = password.trim();
			updateObj.setPassword(MD5.md5Encode(password));
			ModelResult<Boolean> result = investorService.updateInvestor(updateObj);
			if (result.isSuccess()) {
				return BaseRestResult.buildRestResult(true);
			}
			return BaseRestResult.error("修改登录密码失败，请联系管理员");
		}else{
			return BaseRestResult.error("短信验证码校验失败");
		}
	}
	
	@RequestMapping(value = "/register/submit")
	public BaseRestResult<?> register(HttpServletRequest request, RegisterForm registerForm) {
		if(StringUtil.isEmpty(registerForm.getMobile())){
			return BaseRestResult.buildRestResult("手机号码不能为空");
		}
		if(StringUtil.isEmpty(registerForm.getPassword())){
			return BaseRestResult.buildRestResult("密码不能为空");
		}
		if(StringUtil.isEmpty(registerForm.getSmsCode())){
			return BaseRestResult.buildRestResult("短信验证码不能为空");
		}
		//校验短信验证码
		ModelResult<Boolean> checkResult = msgSmsService.useAuthCode(registerForm.getMobile(), registerForm.getSmsCode());
		if(checkResult.isSuccess() && checkResult.getModel()){
			InvestorEntity investor=new InvestorEntity();
			try {
				BeanUtils.copyProperties(investor, registerForm);
			} catch (Exception e) {
				e.printStackTrace();
			}
			String regIp=CusAccessObjectUtil.getIpAddress(request);
			investor.setRegIp(regIp);
			investor.setChannel(InvestorEntity.REGISTER_CHANNEL_H5);
			investor.setAccount(investor.getMobile());
			ModelResult<Boolean> modelResult = investorService.register(investor);
			if (modelResult.isSuccess() && modelResult.getModel()) {
				String pw=MD5.md5Encode(investor.getPassword().trim());
				ModelResult<InvestorEntity> mr = investorService.queryInvestorByLogin(investor.getAccount(), pw);
				if (mr.isSuccess()) {
					investor = mr.getModel();
					if (investor != null) {
						HttpSession session = request.getSession();
						session.removeAttribute("member");
						session.setAttribute("member", investor);
					}
				}
				return BaseRestResult.buildRestResult(true);
			}else{
				return BaseRestResult.buildRestResult(modelResult.getErrMsg());
			}
		}else{
			return BaseRestResult.buildRestResult("短信验证码验证失败");
		}
	}
}
